package org.yunai.swjg.server.module.player.operation;

import org.yunai.swjg.server.core.service.Online;
import org.yunai.swjg.server.core.service.OnlineContextService;
import org.yunai.swjg.server.core.service.OnlineState;
import org.yunai.swjg.server.entity.PlayerEntity;
import org.yunai.swjg.server.module.inventory.Inventory;
import org.yunai.swjg.server.module.inventory.InventoryService;
import org.yunai.swjg.server.module.player.PlayerMapper;
import org.yunai.swjg.server.module.player.vo.Player;
import org.yunai.swjg.server.module.quest.QuestDiary;
import org.yunai.yfserver.async.IIoSerialOperation;
import org.yunai.yfserver.spring.BeanManager;

/**
 * 角色相关信息加载操作
 * User: yunai
 * Date: 13-4-5
 * Time: 下午6:03
 */
public class PlayerInfoLoadOperation implements IIoSerialOperation {

    private static PlayerMapper playerMapper;
    private static InventoryService inventoryService;
    private static OnlineContextService onlineContextService;
    static {
        playerMapper = BeanManager.getBean(PlayerMapper.class);
        inventoryService = BeanManager.getBean(InventoryService.class);
        onlineContextService = BeanManager.getBean(OnlineContextService.class);
    }

    private volatile Online online;
    private final Integer playerId;

    /**
     * 加载数据结果
     */
    private volatile boolean loaded = false;
    /**
     * 加载的任务信息
     */
    private volatile QuestDiary questDiary;

    public PlayerInfoLoadOperation(Online online, Integer playerId) {
        this.online = online;
        this.playerId = playerId;
    }

    @Override
    public State doStart() {
//        session.getOnline().setState(OnlineState.load_roleing);
        return State.STARTED;
    }

    @Override
    public State doIo() {
        // TODO 以后加载角色相关信息
        // TODO 少个异常断开
        if (online.isConnected()) {
            // 角色基本信息
            PlayerEntity playerEntity = playerMapper.selectPlayerByUidAndServerId(online.getUser().getId(), online.getServerId());
            online.setPlayer(Player.build(online, playerEntity));
            Player player = online.getPlayer();
            // 背包信息
            Inventory inventory = inventoryService.loadInventory(player);
            online.setInventory(inventory);
            // 任务信息
            questDiary = new QuestDiary(online);
            online.setQuestDiary(questDiary);
            questDiary.load();

            loaded = true;
        }
        return State.IO_DONE;
    }

    @Override
    public State doFinish() {
        // TODO loaded == false 的情况 断开用户连接
        if (online.isConnected() && loaded) {
            // 切换状态
            online.setState(OnlineState.load_roled);
            // 添加到onlineContextService
            onlineContextService.addPlayer(online);
            // 玩家登录初始化
            online.login();
        }
        return State.FINISHED;
    }

    @Override
    public Integer getSerialKey() {
        return playerId;
    }
}
